<template>
  <div ref="chartRef" :style="{ width: '100%', height: '300px' }"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  props: {
    data: {
      type: Array,
      default: () => []
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chartInstance: null
    };
  },
  watch: {
    data: {
      handler() {
        this.initChart();
      },
      deep: true
    }
  },
  mounted() {
    this.initChart();
  },
  methods: {
    initChart() {
      if (this.chartInstance) {
        this.chartInstance.dispose();
      }
      this.chartInstance = echarts.init(this.$refs.chartRef);
      const option = {
      title: { text: this.title, left: 'center' },
      tooltip: { trigger: 'item' },
      legend: {
        orient: 'horizontal', // 水平排列图例
        bottom: 0,           // 贴紧底部
        padding: [10, 0],    // 上下留白避免遮挡
        itemGap: 20,         // 图例项间距
        textStyle: { fontSize: 12 }
      },
      series: [{
        name: this.title,
        type: 'pie',
        radius: '50%',
        center: ['50%', '45%'], // 饼图位置上移，为底部图例留空间[5](@ref)
        data: this.data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      this.chartInstance.setOption(option);
    }
  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  }
};
</script>